<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addBtn">添加</button>
      <button @click="clearFn">修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(obj, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ obj["name"] }}</td>
          <td>{{ obj["age"] }}</td>
          <td>{{ obj["gender"] }}</td>
          <td>
            <button @click="deleFn(obj.id)">删除</button>
            <button @click="escFn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      i:'',
      name: "", //名字
      age: "", //年龄
      gender: "", //性别
      arr:JSON.parse(localStorage.getItem("Arr"))||[]
    };
  },
  methods: {
    addBtn() {
      // 判断不能为空
      if (this.name.trim().length === 0 || this.age === 0) {
        alert("不能为空");
        return;
      }
      // 无数据再新增，id 要判断一下
      let id = this.arr.length > 0 ? this.arr[this.arr.length - 1].id + 1 : 1;
      this.arr.push({
        // 当前数组的最后一个对象的id+1作为新对象的id
        id: id,
        name: this.name,
        age: this.age,
        gender: this.gender,
      });
      this.name= "", //名字
      this.age="", //年龄
      this.gender= "" //性别
    },
    deleFn(id) {
      let index = this.arr.findIndex((obj) => {
        obj.id === id;
      });
      this.arr.splice(index, 1);
    },
     escFn(index){
    // this.name=this.arr[index].name
     this.name=this.arr[index].name
    this.age=this.arr[index].age
    this.gender=this.arr[index].gender
    this.i=index
  },
  clearFn(){
     if (this.name.trim().length === 0 || this.age === 0) {
        alert("不能为空");
        return;
      }
    this.arr[this.i].name= this.name
    this.arr[this.i].age=this.age
    this.arr[this.i].gender=this.gender

    
  }
  },
  watch:{
    arr:{
      handler(){
// 存入本地、
localStorage.setItem("Arr",JSON.stringify(this.arr))
      },
      deep:true
    }
  },
 
};
</script>
